package com.fuyun.microservice.handler;

import com.fuyun.microservice.codec.PacketType;
import com.fuyun.microservice.codec.msg.Header;
import com.fuyun.microservice.codec.msg.LoginRequestMessage;
import com.fuyun.microservice.codec.msg.LoginResponseMessage;
import com.fuyun.microservice.config.ClientPrivilegeProperties;
import com.fuyun.microservice.connect.SessionManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@ChannelHandler.Sharable
public class LoginHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    private SessionManager sessionManager;


    public LoginHandler(SessionManager sessionManager){
        this.sessionManager = sessionManager;

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        Header header=msg.getHeader();
        if(header.getCommandId()!= PacketType.CONNECTREQUEST.getCommandId()){
            ctx.fireChannelRead(msg);
            return;
        }

        log.debug("login message:"+msg.toString());
        int clientId=msg.getClientId();
        String clientSecret=msg.getClientSecret();
        LoginResponseMessage loginResponseMessage=new LoginResponseMessage(header.getSequenceNo());
        boolean hasPrivilege=  sessionManager.addChannel(clientId,clientSecret,ctx.channel());

        if(hasPrivilege){
            loginResponseMessage.setRspCode(1);
            loginResponseMessage.setRspMessage("login success");
            ctx.writeAndFlush(loginResponseMessage);
        }else{
            loginResponseMessage.setRspCode(0);
            loginResponseMessage.setRspMessage("login failed");
            ctx.writeAndFlush(loginResponseMessage);
            Thread.sleep(100L);
            ctx.channel().close();
        }

        ctx.fireChannelReadComplete();
    }

}
